const {
	isObject,
	isArray
} = Require("utils.libs.src.dao-type");
//构造不同xml内容
function buildXML(obj, rootName = 'xml', level = 0) {
	const content = Object.keys(obj).map(item => {
		//处理数组，key强制设置为item
		if (isArray(obj[item])) {
			let arr = obj[item].map(e => {
				return buildXML(e, 'item', level + 1)
			})
			return `<${item}>${arr.join('')}</${item}>`
		} else if (isObject(obj[item])) {
			// return `<${item}><![CDATA[${JSON.stringify(obj[item])}]]></${item}>`
			return buildXML(obj[item], item, level + 1)
		} else {
			return `<${item}>${obj[item]}</${item}>`
		}
	})
	let header = ""
	if (level == 0) {
		header = `<?xml version="1.0" encoding="GBK"?>`
	}
	return `${header}<${rootName}>${content.join('')}</${rootName}>`
}
// 简易版Object转XML，只可在微信支付时使用，不支持嵌套
function buildXMLWx(obj, rootName = 'xml') {
	const content = Object.keys(obj).map(item => {
		//处理数组，key强制设置为item
		if (isArray(obj[item])) { // 数组
			let arr = obj[item].map(e => {
				return buildXMLWx(e, 'item')
			})
			return `<${item}>${arr.join('')}</${item}>`
		} else if (isObject(obj[item])) { // 对象
			// return `<${item}><![CDATA[${JSON.stringify(obj[item])}]]></${item}>`
			return `${buildXMLWx(obj[item],item)}`
		} else { // 其他
			return `<${item}><![CDATA[${obj[item]}]]></${item}>`
		}
	})
	return `<${rootName}>${content.join('')}</${rootName}>`
}
// 简易版XML转Object，只可在微信支付时使用，不支持嵌套
function parseXML(xml) {
	const xmlReg = /<(?:xml|root).*?>([\s|\S]*)<\/(?:xml|root)>/;
	const str = xmlReg.exec(xml)[1];
	const obj = {};
	const nodeReg = /<(.*?)>(?:<!\[CDATA\[){0,1}(.*?)(?:\]\]>){0,1}<\/.*?>/g;
	let matches = null;
	// eslint-disable-next-line no-cond-assign
	while ((matches = nodeReg.exec(str))) {
		obj[matches[1]] = matches[2];
	}
	return obj
}

module.exports = {
	parseXML,
	buildXML,
	buildXMLWx
};
